<?php

namespace app\common\model;

use think\Model;
use think\model\concern\SoftDelete;

abstract class Base extends Model
{
    use SoftDelete;

    // 定义时间戳字段名
    protected $createTime        = 'created_at';
    protected $updateTime        = 'updated_at';
    protected $deleteTime        = 'deleted_at';
    protected $defaultSoftDelete = '0000-00-00 00:00:00';
    protected $readonly          = ['id', 'created_at', 'tenant_id'];
    protected $tenantId          = 0;
    protected $whereField        = [];

    protected static function getTenantId(): int
    {
        return intval(TENANTID);
    }

    public function __construct(array $data = [])
    {
        $this->tenantId = self::getTenantId();
        parent::__construct($data);
    }

    // 定义全局的查询范围
    protected $globalScope = ['tenantId'];

    public function scopeTenantId($query)
    {
        //全局注入租户id
        $query->where('tenant_id', $this->tenantId);
    }

    /**
     * 自动插入租户id
     * @param Model $model
     * @return mixed|void
     */
    public static function onBeforeInsert($model)
    {

        $model->tenant_id = self::getTenantId();
    }

    /**
     * 生成查询条件
     * @param $data 查询数据[key=>value]
     * @return array 查询条件
     */
    public function buildWhere($data)
    {
        $arr = [];
        foreach ($data as $k => $v) {
            if (isset($this->whereField[$k][1]) && $v) {
                $arr[] = [$k, $this->whereField[$k][0], str_replace('{value}', $v, $this->whereField[$k][1])];
            }
        }
        return $arr;
    }
}
